//控制层
app.controller('goodsController', function ($scope, $controller, goodsService, uploadimgservice, itemCatService, typeTemplateService) {

    $controller('baseController', {$scope: $scope});//继承

    //读取列表数据绑定到表单中  
    $scope.findAll = function () {
        goodsService.findAll().success(
            function (response) {
                $scope.list = response;
            }
        );
    }

    //分页
    $scope.findPage = function (page, rows) {
        goodsService.findPage(page, rows).success(
            function (response) {
                $scope.list = response.rows;
                $scope.paginationConf.totalItems = response.total;//更新总记录数
            }
        );
    }

    //查询实体
    $scope.findOne = function (id) {
        goodsService.findOne(id).success(
            function (response) {
                $scope.entity = response;
            }
        );
    }

    //保存
    $scope.save = function () {
        var serviceObject;//服务层对象
        if ($scope.entity.id != null) {//如果有ID
            serviceObject = goodsService.update($scope.entity); //修改
        } else {
            serviceObject = goodsService.add($scope.entity);//增加
        }
        serviceObject.success(
            function (response) {
                if (response.success) {
                    //重新查询
                    $scope.reloadList();//重新加载
                } else {
                    alert(response.message);
                }
            }
        );
    }


    //批量删除
    $scope.dele = function () {
        //获取选中的复选框
        goodsService.dele($scope.selectIds).success(
            function (response) {
                if (response.success) {
                    $scope.reloadList();//刷新列表
                    $scope.selectIds = [];
                }
            }
        );
    }

    $scope.searchEntity = {};//定义搜索对象

    //搜索
    $scope.search = function (page, rows) {
        goodsService.search(page, rows, $scope.searchEntity).success(
            function (response) {
                $scope.list = response.rows;
                $scope.paginationConf.totalItems = response.total;//更新总记录数
            }
        );
    }

    /***************************************************************************************/
    //定义添加对象
    $scope.entity = {
        tbGoods: {
            isEnableSpec: 0
        },
        tbGoodsDesc: {
            //商品图片信息列表
            itemImages: [],
            //扩展属性列表
            customAttributeItems: [],
            //选中的规格列表
            specificationItems: []
        },
        itemList: []
    }


    //添加商品
    $scope.add = function () {

        //获取到富文本编辑器中的html内容
        $scope.entity.tbGoodsDesc.introduction = editor.html();

        goodsService.add($scope.entity).success(
            function (response) {

                alert(response.message);

                if (response.success) {
                    //清空实体便于下一次添加数据
                    $scope.entity = {}

                    //清空富文本编辑器
                    editor.html("");

                    //清空复选框
                    $scope.specList = []
                }
            }
        );
    }

    //商品图片上传
    $scope.goodsImgEntity = {};

    $scope.uploadimg = function () {

        uploadimgservice.uploadimg().success(function (response) {

            if (response.error == 0) {
                $scope.goodsImgEntity.url = response.url;
            }

        })

    }

    //将商品图片信息添加到数组
    $scope.addGoodsItemImages = function () {

        $scope.entity.tbGoodsDesc.itemImages.push($scope.goodsImgEntity);

    }

    //从数组中删除商品图片信息
    $scope.removeGoodsItemImages = function ($index) {
        $scope.entity.tbGoodsDesc.itemImages.splice($index, 1);
    }

    //分类列表查询
    $scope.itemCat1List = [];
    $scope.itemCat2List = [];
    $scope.itemCat3List = [];
    //品牌列表
    $scope.brandList = [];

    $scope.findByParentId = function (pid, level) {

        itemCatService.findByParentId(pid).success(function (response) {
            responseList = response;

            if (level == 1) {
                $scope.itemCat1List = response;
            } else if (level == 2) {
                $scope.itemCat2List = response;
            } else {
                $scope.itemCat3List = response;
            }
        })

    }

    //监听一级分类变化
    $scope.$watch('entity.tbGoods.category1Id', function (newVal, oldVal) {

        if (newVal != undefined) {
            $scope.findByParentId(newVal, 2);
        }

        $scope.itemCat3List = [];

    })

    //监听二级分类变化
    $scope.$watch('entity.tbGoods.category2Id', function (newVal, oldVal) {
        if (newVal != undefined) {
            $scope.findByParentId(newVal, 3);
        }

    })

    //监听三级分类变化
    $scope.$watch('entity.tbGoods.category3Id', function (newVal, oldVal) {
        if (newVal != undefined) {
            //根据三级分类查询模板
            itemCatService.findOne(newVal).success(function (response) {

                //模板id赋值
                $scope.entity.tbGoods.typeTemplateId = response.typeId;

                //查询模板
                typeTemplateService.findOne(response.typeId).success(function (result) {
                    //给品牌列表赋值
                    $scope.brandList = JSON.parse(result.brandIds);

                    //给扩展属性赋值
                    $scope.entity.tbGoodsDesc.customAttributeItems = JSON.parse(result.customAttributeItems);
                })

                //查询规格列表
                typeTemplateService.findSpecification(response.typeId).success(function (response2) {

                    $scope.specList = response2;

                })
            });
        }

    })

    //更新规格选项列表复选框状态
    $scope.updateItemsListState = function ($event, text, itemName) {

        //根据key和value查询对象是否存在
        var obj = $scope.findObjectByKey($scope.entity.tbGoodsDesc.specificationItems, 'name', text);

        //存在
        if (obj != null) {

            //判断选中状态
            if ($event.target.checked) {

                //选中
                obj.values.push(itemName);

            } else {
                //取消选中,将规格名从values数组中删除
                obj.values.splice(obj.values.indexOf(itemName), 1);

                //移除完判断values是否为空数组
                if (obj.values.length == 0) {
                    //将数组所在规格对象删除
                    $scope.entity.tbGoodsDesc.specificationItems.splice($scope.entity.tbGoodsDesc.specificationItems.indexOf(obj), 1);
                }
            }

        } else {
            //不存在
            $scope.entity.tbGoodsDesc.specificationItems.push({'name': text, 'values': [itemName]})
        }

    }

    //每次点击规格选项去更新entity.itemList 集合
    $scope.updateItemsLIst = function () {
        //先定义一个初始默认sku列表   ps：最后要存储的数据结构
        $scope.entity.itemList = [{spec:{}/*存放可变的sku规格组合对象*/,price: 0,num: 9999,status: "1",isDefault: "0"}];

        //浅克隆 已经选中的规格选项列表，把名字简化
        $scope.specCheckedList = $scope.entity.tbGoodsDesc.specificationItems;
        
        //循环选中表中已有的的规格名列表  ps:相当于逻辑上添加一个展示效果列
        for (let i in $scope.specCheckedList) {

            //定义一个空的新集合？
            var newList = [];


            //循环 默认或上一次sku列表，并在其基础上生成一个新曾规格的sku列表
            for (let j in $scope.entity.itemList) { //：遍历每一行数据



                //循环选中的规格所属选项列表 获取当中的每一个选项，并将选项添加到行内产生新行然后放入新的集合
                for (let k in $scope.specCheckedList[i].values) { //遍历每一个values中的选项名



                    //通过深克隆复制一行与原来数据完全一致但引用地址不同的新行，  ps：必须通过深克隆，不操作原来数据
                    var newRow = JSON.parse(JSON.stringify($scope.entity.itemList[j]));

                    //在新行中添加选中的value ,key是选项名 value是规格名
                    newRow.spec[$scope.specCheckedList[i].name] = $scope.specCheckedList[i].values[k];

                    //将新产生的行添加到新集合中
                    newList.push(newRow);


                }


            }

            //产生的新的集合赋值给最终结果
            $scope.entity.itemList = newList;

        }
    }

});	
